package com.tianqingwl.gsystem.sysuser.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianqingwl.gsystem.common.vo.CommonResultVo;
import com.tianqingwl.gsystem.common.vo.PageResultVo;
import com.tianqingwl.gsystem.common.vo.ResultVo;
import com.tianqingwl.gsystem.sysuser.pojo.SysUser;
import com.tianqingwl.gsystem.sysuser.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/manage/user")
@PreAuthorize("@gs.check('sys_user_manage')")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/list")
    @ResponseBody
    public Object list(Long page, Long limit, Integer searchType, String searchStr) {
        page = page == null ? 1 : page;
        limit = limit == null ? 10 : limit;

        Page<SysUser> userPage = new Page<>(page, limit);
        sysUserService.listSysUserPage(userPage, searchType, searchStr);

        return PageResultVo.success(userPage.getTotal(), userPage.getPages(), userPage.getRecords());
    }

    @GetMapping("/user-manage.html")
    public String userManagePage() {
        return "manage/user/user-manage";
    }

    @GetMapping("/user-edit.html")
    public String permissionEdit(Model model, Long userId) {
        if (userId != null) {
            //修改查询
            SysUser sysUser = sysUserService.getUserById(userId);
            if (sysUser == null) {
                return "redirect:404.html";
            }
            model.addAttribute("sysUser", sysUser);
        }

        return "manage/user/user-edit";
    }

    @GetMapping("/user-role.html")
    public String userRolePage() {
        return "manage/user/user-role";
    }

    @GetMapping("/user-role-select.html")
    public String userRoleSelectPage() {
        return "manage/user/user-role-select";
    }

    @PostMapping({"/userSave"})
    @ResponseBody
    public ResultVo userSave(SysUser sysUser) {
        if (sysUser == null) {
            return CommonResultVo.fail("未传入数据");
        }
        try {
            SysUser currentUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (sysUser.getUserId()!=null){
                if (sysUser.getUserId()==1&&currentUser.getUserId()!=1){
                    return CommonResultVo.fail("不可修改超级管理员");
                }
            }

            SysUser saveResult = sysUserService.save(sysUser);
            return CommonResultVo.success(saveResult);
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }

    @PostMapping({"/userSetting"})
    @ResponseBody
    public ResultVo userSetting(SysUser sysUser) {
        if (sysUser == null) {
            return CommonResultVo.fail("未传入数据");
        }
        SysUser user = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        sysUser.setUserId(user.getUserId());
        try {
            SysUser saveResult = sysUserService.save(sysUser);
            SysUser newUserInfo = sysUserService.getUserById(user.getUserId());
            newUserInfo.setAuthorities(user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(newUserInfo, newUserInfo.getPassword(), user.getAuthorities()));
            return CommonResultVo.success();
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }

    @PostMapping({"/updatePassword"})
    @ResponseBody
    public ResultVo updatePassword(String oldPassword, String newPassword1, String newPassword2) {
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword1) || StringUtils.isEmpty(newPassword2)) {
            return CommonResultVo.fail("未传入数据");
        }
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUser userInfo = sysUserService.getUserById(sysUser.getUserId());
        if (!passwordEncoder.matches(oldPassword, userInfo.getPassword())) {
            return CommonResultVo.fail("原密码输入错误，不能修改密码");
        }
        if (!newPassword1.equals(newPassword2)) {
            return CommonResultVo.fail("确认密码输入不一致");
        }
        try {

            sysUserService.updateSysUserPassword(sysUser.getUsername(), newPassword1);
            return CommonResultVo.success();
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }

    @GetMapping({"/delete"})
    @ResponseBody
    public ResultVo delete(Long userId, Long[] userIds) {
        try {
            SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (userId != null) {
                if (userId == 1) {
                    return CommonResultVo.fail("不能删除默认用户");
                }
                sysUserService.deleteById(userId);
            } else if (userIds != null && userIds.length > 0) {
                List<Long> userIdList = Arrays.asList(userIds);
                if (userIdList.contains(1L)){
                    return CommonResultVo.fail("不能删除默认用户");
                }
                sysUserService.deleteByIds(userIdList);
            } else {
                return CommonResultVo.fail("no id");
            }
            return CommonResultVo.success();
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }

    @PostMapping({"/userAddRole"})
    @ResponseBody
    public ResultVo userAddRole(Long userId, Long[] roleIds) {

        if (userId == null || roleIds == null || roleIds.length == 0) {
            return CommonResultVo.fail("参数不足");
        }
        try {
            SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (userId==1&&sysUser.getUserId()!=1){
                return CommonResultVo.fail("不可操作超级管理员的角色");
            }
            sysUserService.addRole(userId, roleIds);
            return CommonResultVo.success();
        } catch (Exception e) {
            return CommonResultVo.fail(e.getMessage());
        }
    }

    @GetMapping("/user-setting.html")
    public String userSettingPage(Model model) {
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        model.addAttribute("currentUser", sysUser);
        return "manage/user/user-setting";
    }

    @GetMapping("/user-password.html")
    public String userPasswordPage() {
        return "manage/user/user-password";
    }
}
